// 帖子详情页面功能
$(document).ready(function () {
  // 检查登录状态，如果未登录则重定向到登录页
  const token = localStorage.getItem('jwt_token');
  if (!token) {
    window.location.href = 'login.html';
    return;
  }

  let postId = getQueryParam('id');
  let postData = null;

  // 加载帖子详情
  function loadPostDetail() {
    if (!postId) {
      showError('帖子ID不存在');
      return;
    }

    request({
      url: `/posts/${postId}`,
      method: 'GET',
      success: function (response) {
        if (response.data) {
          postData = response.data;
          renderPostDetail(postData);
          loadComments();
        } else {
          showError('加载帖子失败');
        }
      },
      error: function () {
        showError('网络错误，请稍后重试');
      }
    });
  }

  // 渲染帖子详情
  function renderPostDetail(post) {
      // 检查是否为精华帖子
      const isFeatured = post.isFeatured === 1;
      const featuredBadge = isFeatured ? '<span class="featured-badge" style="background: #e74c3c; color: white; padding: 4px 12px; border-radius: 16px; font-size: 14px; margin-left: 15px; font-weight: bold; vertical-align: middle;">精华帖子</span>' : '';
      
      $('#post-title').html(post.title + featuredBadge);
      $('#post-author').text(post.nickname || '匿名用户');
      $('#post-time').text(formatDateTime(post.createTime));
      $('#post-category').text(getCategoryName(post.categoryId));
      $('#post-body').html(post.content || '<p>暂无内容</p>');
      $('#like-count').text(post.likeCount || 0);
  }

  // 加载评论
  function loadComments() {
    request({
      url: `/posts/${postId}/comments`,
      method: 'GET',
      success: function (response) {
        if (response.data) {
          renderComments(response.data);
          $('#comment-count').text(response.data.totalCount || 0);
        } else {
          showError('加载评论失败');
        }
      },
      error: function () {
        console.error('加载评论失败');
      }
    });
  }

  function checkLike() {
    request({
      url: `/posts/${postId}/like`,
      method: 'GET',
      success: function (response) {
        if (response.code == 200) {
          if (response.data) {
            $('#like-btn').css('background-color', '#3498db');
            $('#like-btn').text('取消点赞');
          } else {
            $('#like-btn').css('background-color', '#e74c3c');
            $('#like-btn').text('点赞');
          }
          $('#like-btn').css('background-color', '#3498db');
        } else {
          $('#like-btn').css('background-color', '#e74c3c');
        }
      },
      error: function () {
      }
    })
  }

  // 渲染评论列表
  function renderComments(comments) {
    const $commentsList = $('#comments-list');
    $commentsList.empty();

    if (comments.length === 0) {
      $commentsList.html('<div style="text-align: center; padding: 40px; color: #95a5a6; font-style: italic;">暂无评论，快来发表第一条评论吧！</div>');
      return;
    }

    comments.forEach((comment, index) => {
      // 使用不同的边框颜色交替显示评论
      const borderColors = ['#3498db', '#e74c3c', '#27ae60', '#f39c12', '#9b59b6'];
      const borderColor = borderColors[index % borderColors.length];

      const commentHtml = `
                <div class="comment-item" style="background: #f8f9fa; border-radius: 8px; padding: 20px; margin-bottom: 15px; border-left: 4px solid ${borderColor}; transition: transform 0.2s, box-shadow 0.2s;">
                    <div class="comment-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                        <span class="comment-author" style="color: #2c3e50; font-weight: 500; font-size: 14px;">
                            <span style="display: inline-block; width: 32px; height: 32px; background: ${borderColor}; color: white; border-radius: 50%; text-align: center; line-height: 32px; margin-right: 10px; font-weight: bold;">
                                ${(comment.nickname || '匿名用户').charAt(0).toUpperCase()}
                            </span>
                            ${escapeHtml(comment.nickname || '匿名用户')}
                        </span>
                        <span class="comment-time" style="color: #7f8c8d; font-size: 12px;">${formatDateTime(comment.createTime)}</span>
                    </div>
                    <div class="comment-content" style="color: #34495e; line-height: 1.6; font-size: 14px; padding-left: 42px;">
                        ${escapeHtml(comment.content).replace(/\n/g, '<br>')}
                    </div>
                </div>
            `;
      $commentsList.append(commentHtml);
    });

    // 添加悬停效果
    $('.comment-item').hover(
      function () {
        $(this).css({
          transform: 'translateY(-2px)',
          boxShadow: '0 4px 8px rgba(0,0,0,0.1)'
        });
      },
      function () {
        $(this).css({
          transform: 'translateY(0)',
          boxShadow: 'none'
        });
      }
    );
  }

  // 点赞功能
  $('#like-btn').on('click', function () {
    request({
      url: `/posts/${postId}/like`,
      method: 'POST',
      success: function (response) {
        if (response.code == 200) {
          const currentLikes = parseInt($('#like-count').text());
          $('#like-count').text(currentLikes + 1);
          alert('点赞成功！');
        } else {
          showError(response.message || '点赞失败');
        }
      },
      error: function (jqXHR) {
        if (jqXHR.status === 409) {
          showError('您已经点过赞了');
        } else {
          showError('点赞失败，请稍后重试');
        }
      }
    });
  });

  // 发表评论
  $('#submit-comment').on('click', function () {
    const content = $('#comment-content').val().trim();

    if (!content) {
      showError('请输入评论内容');
      return;
    }

    if (content.length > 500) {
      showError('评论内容不能超过500字');
      return;
    }

    request({
      url: `/posts/${postId}/comments`,
      method: 'POST',
      data: {
        content: content
      },
      success: function (response) {
        if (response.code == 200) {
          $('#comment-content').val('');
          loadComments(); // 重新加载评论列表
          alert('评论发表成功！');
        } else {
          showError(response.message || '评论失败');
        }
      },
      error: function () {
        showError('评论失败，请稍后重试');
      }
    });
  });

  // 获取分类名称
  function getCategoryName(categoryId) {
    const categories = {
      '1': '学习交流',
      '2': '校园生活',
      '3': '二手交易',
      '4': '社团活动',
      '5': '其他'
    };
    return categories[categoryId] || '未知分类';
  }

  // HTML转义函数
  function escapeHtml(text) {
    const map = {
      '&': '&',
      '<': '<',
      '>': '>',
      '"': '"',
      "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, function (m) { return map[m]; });
  }

  // 检查用户权限
  function checkUserPermissions() {
    const userInfo = localStorage.getItem('user_info');
    if (userInfo) {
      try {
        const user = JSON.parse(userInfo);
        if (user.role === 'banned') {
          $('#like-btn').prop('disabled', true);
          $('#submit-comment').prop('disabled', true);
          $('#comment-content').prop('disabled', true);
          $('#comment-content').attr('placeholder', '您已被禁言，无法发表评论');
        }
      } catch (e) {
        console.error('解析用户信息失败');
      }
    }
  }

  // 初始化页面
  function initPage() {
    if (!postId) {
      showError('无效的帖子ID');
      setTimeout(() => {
        window.location.href = 'index.html';
      }, 2000);
      return;
    }

    loadPostDetail();
    checkUserPermissions();
    checkLike()
  }

  // 启动页面初始化
  initPage();
});
